package com.abocode.smarten.client.netty;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Description:
 * Define a  {@code NamedThreadFactory} implementations {@link ThreadFactory}.
 *
 * @author: guanxianfei
 * @date: 2019/7/24
 */
public class NamedThreadFactory implements ThreadFactory {
    private static final AtomicInteger POOL_SEQ = new AtomicInteger(1);
    private final AtomicInteger mThreadNum = new AtomicInteger(1);

    private final String prefixThread;

    private final boolean threadDaemo;

    private final ThreadGroup threadGroup;

    public NamedThreadFactory() {
        this("pool-" + POOL_SEQ.getAndIncrement(), false);
    }

    public NamedThreadFactory(String prefix) {
        this(prefix, false);
    }

    public NamedThreadFactory(String prefix, boolean daemo) {
        prefixThread = prefix + "-thread-";
        threadDaemo = daemo;
        SecurityManager s = System.getSecurityManager();
        threadGroup = (s == null) ? Thread.currentThread().getThreadGroup() : s
                .getThreadGroup();
    }

    public Thread newThread(Runnable runnable) {
        String name = prefixThread + mThreadNum.getAndIncrement();
        Thread thread = new Thread(threadGroup, runnable, name, 0);
        thread.setDaemon(threadDaemo);
        return thread;
    }

    public ThreadGroup getThreadGroup() {
        return threadGroup;
    }
}
